﻿using System;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;
using System.Xml;
using System.IO;

namespace CodeCounsel.StateReports
{
    static class Extensions
    {
        public static XDocument GetXDocument(this OpenXmlPart part)
        {
            XDocument document = new XDocument();
            using (XmlReader reader = XmlReader.Create(part.GetStream(
                FileMode.Open, FileAccess.Read)))
            {
                document = XDocument.Load(reader);
            }
            return document;
        }

        public static void FeedXDocument(this OpenXmlPart part, XDocument document)
        {
            using (XmlWriter writer = XmlWriter.Create(part.GetStream(
                FileMode.Create, FileAccess.Write)))
            {
                document.WriteTo(writer);
            }
        }

        public static MemoryStream OpenMemoryStream(this FileInfo file)
        {
            MemoryStream ms = new MemoryStream();
            using (FileStream fs = file.OpenRead())
            {
                byte[] buffer = new byte[1024];
                int read = 0;
                while ((read = fs.Read(buffer, 0, 1024)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
            }
            return ms;
        }
    }
}
